package com.xdf.xzymanagementsystem.util;

import com.xdf.xzymanagementsystem.config.ShiroRealm;
import com.xdf.xzymanagementsystem.entity.SysRole;
import com.xdf.xzymanagementsystem.entity.SysUser;
import com.xdf.xzymanagementsystem.service.SysRoleService;
import com.xdf.xzymanagementsystem.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 2022年3月16日 07:56:33 chanchaw
 */
@Component
public class ShiroUtils {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    // 返回用户表 sys_user.id
    public static Object getUserPK(){
        return SecurityUtils.getSubject().getPrincipal();
    }
    public static Integer getUserPKInteger(){
        Object userPK = getUserPK();
        return Integer.parseInt((String)userPK);
    }

    // 返回用户对象
    public SysUser getCurrentUser() {
        Object userPK = getUserPK();
        Integer userId = Integer.parseInt((String)userPK);
        SysUser user = null;
        try {
            user = sysUserService.selectByPrimaryKey(userId);
        } catch (Exception e) {
            throw new RuntimeException("查询获取当前用户时出现异常！");
        }
        return user;
    }

    // 返回当前用户是否是管理员
    public Boolean isAdmin(){
        Integer userId = getUserPKInteger();
        List<SysRole> sysRoleList = Optional.ofNullable(sysRoleService.getUserAdmin(userId)).orElse(new ArrayList<>());
        return sysRoleList.size() > 0 ? true : false;
    }

    /**
     * 刷新指定用户的权限缓存
     * @param principal 用户主键
     */
    public static void reloadAuthorizing(Object principal) {
        RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        ShiroRealm myShiroRealm = (ShiroRealm) rsm.getRealms().iterator().next();

        Subject subject = SecurityUtils.getSubject();
        String realmName = subject.getPrincipals().getRealmNames().iterator().next();
        SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, realmName);
        subject.runAs(principals);
        if(myShiroRealm.isAuthenticationCachingEnabled()) {
            myShiroRealm.getAuthenticationCache().remove(principals);
        }
        if(myShiroRealm.isAuthorizationCachingEnabled()) {
            // 删除指定用户shiro权限
            myShiroRealm.getAuthorizationCache().remove(principals);
        }
        // 刷新权限
        subject.releaseRunAs();
    }

    // 刷新拥有指定角色的所有用户的权限缓存
    public void reloadPermissions8RoleId(Integer roleId){
        List<SysUser> sysUserList = sysUserService.getUsers8Role(roleId);
        if(sysUserList == null || sysUserList.size()<=0) return;

        sysUserList.forEach(item -> reloadAuthorizing(item.getId()));
    }

    public void reloadPermissions8RoleId(List<Integer> roleIdList){
        if(roleIdList == null || roleIdList.size()<=0) return;
        roleIdList.forEach(roleId ->{
            List<SysUser> sysUserList = sysUserService.getUsers8Role(roleId);
            if(sysUserList != null && sysUserList.size()>0)
                sysUserList.forEach(user -> reloadAuthorizing(user.getId()));
        });


    }
}
